package model;

import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Transient;



@Entity

public class Ur {
	@OneToMany
	private Set<Tid> observers;
	@Transient
	private Timer t = new Timer();
	@Transient
	private TimerTask tt;
	private static Ur uniqueInstance;
	@Id
	private int id = 1;
	
	
	private Ur() {
		observers = new HashSet<Tid>();
		Date d = new Date();
		d.setTime(d.getTime()+1000);
		tt = new TimerTask(){
			public void run() {

				notifyObservers();
				}
		};
		t.scheduleAtFixedRate(tt, d, 1000);
	}

	public static Ur getInstance() {
		if (uniqueInstance == null) {
			uniqueInstance = new Ur();
		}
		return uniqueInstance;
	}
	
	
	public Set<Tid> getObs(){
		return observers;
	}

	

	
	public void registerObserver(Tid o) {
		observers.add(o);
	}

	
	public void removeObserver(Tid o) {
		observers.remove(o);

	}

	private void notifyObservers() {
		Iterator<Tid> itr = observers.iterator();
		while (itr.hasNext()) {
			Tid  o = itr.next();
			o.update();
		}
	}

}
